package com.ptszyxx.popose.module.main.home.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.enums.HomeTabEnum;
import com.ptszyxx.popose.common.event.HomeTabEvent;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YLoginUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.RxBus;
import com.ysg.bus.RxSubscriptions;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.http.BaseListResponse;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessListResult;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.entity.home.HomeResult;
import com.ysg.http.data.entity.login.LoginResult;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDbUtils;
import com.ysg.utils.YPhoneUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class HomeWorldVM extends BaseViewModel<CommonRepository> {
    public HomeTabEnum tabEnum;
    public String gender = "1";
    public ObservableField<String> sexOnline = new ObservableField<>("1");
    public ObservableField<String> input = new ObservableField<>();
    public int position;

    public HomeWorldVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent onRefreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onChangeSexEvent = new SingleLiveEvent<>();
    }

    public BindingCommand onLoadAccountCommand = new BindingCommand(()-> onLoadAccount());

    //TODO 3.异步通知处理=====================
    public Disposable disposable;
    @Override
    public void registerRxBus() {
        super.registerRxBus();
        disposable = RxBus.getDefault().toObservable(HomeTabEvent.class)
                .subscribe(new Consumer<HomeTabEvent>() {
                    @Override
                    public void accept(HomeTabEvent event){
                        if (event != null && tabEnum == event.getTabEnum()){
                            requestList(event.isRefresh());
                        }
                    }
                });
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(disposable);
    }

    //=========================================接口：start===========================================
    public void requestList(boolean isRefresh){
        if (HomeTabEnum.account == tabEnum){
            requestAccountCache(isRefresh);
        }else if (HomeTabEnum.online == tabEnum){
            requestOnline(isRefresh);
        }else if (HomeTabEnum.near == tabEnum){
            requestNear(isRefresh);
        }else{
            requestCity(isRefresh);
        }
    }

    /**
     * 同城
     */
    public void requestCity(boolean isRefresh){
        if (isRefresh){
            this.page = 1;
        }else {
            this.page++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("pageno", String.valueOf(page));
        map.put("gender", gender);
        HttpUtils.getInstance()
                .list(model.homeCityPage(map), this,
                        new OnSuccessListResult<HomeResult>() {
                            @Override
                            public void onSuccessResult(BaseListResponse<HomeResult> response) {
                                uc.onRefreshEvent.setValue(response.getData());
                            }
                        });
    }

    /**
     * 附近
     */
    public void requestNear(boolean isRefresh){
        if (isRefresh){
            this.page = 1;
        }else {
            this.page++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("pageno", String.valueOf(page));
        map.put("lon", "118.720145");
        map.put("lat", "25.372465");
        HttpUtils.getInstance()
                .list(model.homeNearPage(map), this,
                        new OnSuccessListResult<HomeResult>() {
                            @Override
                            public void onSuccessResult(BaseListResponse<HomeResult> response) {
                                uc.onRefreshEvent.setValue(response.getData());
                            }
                        });
    }

    /**
     * 在线
     */
    public void requestOnline(boolean isRefresh){
        if (isRefresh){
            this.page = 1;
        }else {
            this.page++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("pageno", String.valueOf(page));
        map.put("sex", sexOnline.get());
        HttpUtils.getInstance()
                .list(model.homeOnlineList(map), this,
                        new OnSuccessListResult<HomeResult>() {
                            @Override
                            public void onSuccessResult(BaseListResponse<HomeResult> response) {
                                uc.onRefreshEvent.setValue(response.getData());
                            }
                        });
    }

    /**
     * 在线
     */
    public void requestAccount(String loginNames){
        Map<String, String> map = new HashMap<>();
        map.put("loginNames", loginNames);

        HttpUtils.getInstance()
                .list(model.homeAccount(map), this,
                        new OnSuccessListResult<HomeResult>() {
                            @Override
                            public void onSuccessResult(BaseListResponse<HomeResult> response) {
                                List<HomeResult> list = response.getData();
                                if (YCollectionUtil.isNotEmpty(list)){
                                    for (HomeResult item:list) {
                                        item.setUsernick(item.getNick());
                                        item.setUsericon(item.getPic());
                                    }
                                    uc.onRefreshEvent.setValue(list);
                                }
                                YDbUtils.getInstance().saveHomeTabAccount(list);
                            }
                        });
    }

    public void requestAccountCache(boolean isRefresh){
        List<HomeResult> list = YDbUtils.getInstance().findHomeTabAccount();
        uc.onRefreshEvent.setValue(list);
    }

    /**
     * 登录
     */
    public void requestLogin(String phone, String password){
        Map<String, String> map = new HashMap<>();
        map.put("loginname", phone);
        map.put("password", password);
        map.put("loginType", "1");
        map.put("mobileSpec", YPhoneUtil.getModel());

        HttpUtils.getInstance()
                .data(model.login(map), this,
                        new OnSuccessResult<LoginResult>() {
                            @Override
                            public void onSuccessResult(BaseResponse<LoginResult> response) {
                                YLoginUtil.getInstance().login(HomeWorldVM.this, response.getData());
                            }
                        });
    }


    //=========================================接口：end=============================================

    /**
     * 个人详情
     */
    public void jumpPersonDetail(HomeResult item){
        YActivityUtil.getInstance().jumpHomeWorldDetail(this, String.valueOf(item.getUserid()));
    }

    /**
     * 聊天
     */
    public void jumpChat(HomeResult item){
        if (HomeTabEnum.account == tabEnum){
            YToastUtil.showShort("切换账号，不能操作");
        }else{
            YActivityUtil.getInstance().jumpChat(this, item.getTexcode()+"", item.getUsernick(), item.getUsericon());
        }
    }

    /**
     * 在线tab:切换性别
     */
    private void onChangeSex() {
        sexOnline.set(YStringUtil.eq(1, sexOnline.get())? "2": "1");
        requestOnline(true);
        uc.onChangeSexEvent.call();
    }

    /**
     * 切换账号tab
     */
    private void onLoadAccount() {
        if (YStringUtil.isEmpty(input.get())){
            YToastUtil.showShort(R.string.search_tip);
            return;
        }
        requestAccount(input.get());
    }



}
